package com.tmall.wireless.virtualviewdemo.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ohos.aafwk.content.Intent;
import ohos.agp.utils.TextTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ComponentAbilitySlice extends PreviewActivityAbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        mTemplateName = intent.getStringParam("name");
        String data = intent.getStringParam("data");
        if (!TextTool.isNullOrEmpty(data)) {
            mJsonData = getFastJsonDataFromAsset(data);
        }

        setTitle(mTemplateName);
        preview(mTemplateName, mJsonData);
    }

    private JSONObject getFastJsonDataFromAsset(String name) {
        try {
            String filePath = String.format("assets/app/resources/rawfile/%s", name);
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
            // InputStream inputStream = getAssets().open(name);
            BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = inputStreamReader.readLine()) != null) {
                sb.append(str);
            }
            inputStreamReader.close();
            return JSON.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
